const WebSocket = require('ws');
const express = require("express");
const http = require('http');
const path = require("path");
const fs = require('fs');

const app = express();
app.use(express.static(path.join(__dirname,'.')));

const options = {
    key: fs.readFileSync('fake-keys\\privatekey.pem'),
    cert: fs.readFileSync('fake-keys\\certificate.pem')
};
const server = http.createServer(app);
const wss = new WebSocket.Server({server});

const clients = [];
wss.on('connection', function connection(ws) {
    clients.push(ws);
    ws.on('message', function incoming(message) {
        const data = JSON.parse(message);
        console.log('income',data)
        console.log('connected',clients.length)
        clients.forEach((client) => {
            if (client!== ws) {
                client.send(message,{binary:false});
            }
        });
    });

    ws.on('close', function close() {
        const index = clients.indexOf(ws);
        if (index > -1) {
            clients.splice(index, 1);
        }
    });
});
const port = 80;
server.listen(port,'0.0.0.0',() => {
    console.log(`http:\\localhost:${port}`);
});